package backend.task;

import java.io.File;
import java.util.Collection;
import java.util.Iterator;
import java.util.concurrent.TimeUnit;

import org.apache.commons.io.FileUtils;

import backend.DefaultConf;
import backend.LifecycleAwared;

/**
 * 
 * 
 * @author wuhao
 *
 */
public class FileCleaner implements LifecycleAwared{
	
	private Thread expiredThread = null;
	
	public void init(){
		if(expiredThread!=null){
			expiredThread.interrupt();
		}
		else{
			this.expiredThread = new Thread(){
				public void run(){	
					while (true) {	
						try {
							rmExpiredFile(new File(DefaultConf.defaultWorkingDir),7,CleanTimeUnit.DAY);
							TimeUnit.HOURS.sleep(1);
						} catch (InterruptedException e) {
		
						}
						
					
					}
				}
			};
		}
		expiredThread.setName("Thread-expired");
	}
	
    /**
     * 
     * Delete expired files by specified "TimeUnit" and its units.
     * 
     * @param dir
     * @param units
     * @param timeUnit
     */
    public static void rmExpiredFile(File dir, int units, CleanTimeUnit timeUnit) {
        if (dir == null) {
            return;
        }
        if (dir.isFile()) {
            return;
        }
        Collection<File> files = FileUtils.listFiles(dir, null, false);
        long criterion = computeExpTimespan(units, timeUnit);
        File tmp = null;
        for (Iterator<File> iterator = files.iterator(); iterator.hasNext();) {
            tmp = (File) iterator.next();
            if (!FileUtils.isFileNewer(tmp, criterion)) {
                if (tmp.exists()) {
                    tmp.delete();
                }
            }
        }
    }
    
    enum CleanTimeUnit {

        DAY(24 * 3600 * 1000,"'.'yyyyMMdd"),
        HOUR(3600 * 1000,"'.'yyyyMMddHH"),
        MINUTE(1000,"'.'yyyyMMddHHmm");
           
        private long idx;
        
        private String pattern;
        
        CleanTimeUnit(long idx,String pattern) {
            this.idx = idx;
            this.pattern = pattern;
        }
        public String getPattern(){
        	return this.pattern;
        }
        public long getIdx() {
            return this.idx;
        }
    }

    public static boolean isExpiredTime(int units, CleanTimeUnit unit, long target) {
        long currentTime = System.currentTimeMillis();
        long criterion = unit.getIdx() * units;
        if (currentTime - target > criterion) {
            return true;
        }
        return false;
    }

    private static long computeExpTimespan(int units, CleanTimeUnit timeUnit) {
        return System.currentTimeMillis() - timeUnit.getIdx() * units;
    }

	public void start() {
		if(expiredThread == null){
			init();
		}
		this.expiredThread.start();
	}

	public void halt() {
		if(expiredThread!=null){
			expiredThread.interrupt();
		}
	}


}
